
import type { FormProps } from 'antd';
import { Button, Form, Input, Checkbox } from 'antd';
import { NavBar } from 'antd-mobile';
import axios from '../../api/http'
import { useNavigate } from 'react-router-dom';
import { useState } from 'react';
import title from '../../assets/title.png'

type FieldType = {
  phone?: string;
  code?: string;
  agree?: boolean;
};

function Index() {
  const nav = useNavigate();
  const [countdown, setCountdown] = useState(0);
  const [randomCode, setRandomCode] = useState('');
  const [form] = Form.useForm();
  const [displayCode, setDisplayCode] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('表单提交数据:', values);
    
    // 验证手机号格式
    if(!values.phone){
      alert('请输入手机号');
      return;
    }
    if(!/^1[3-9]\d{9}$/.test(values.phone)){
      alert('请输入正确的手机号');
      return;
    }
    
    if(!values.code){
      alert('请输入验证码');
      return;
    }
    if(!values.agree){
      alert('请同意服务协议');
      return;
    }
    
    // 先在前端校验短信验证码（与生成的随机验证码一致即可）
    if(values.code !== randomCode){
      alert('验证码不正确');
      return;
    }

    // 调用真实后端登录接口
    console.log('发送登录请求:', values);
    setLoading(true);
    
    // 模拟登录成功（因为后端可能没有实现）
    // 在实际项目中，这里应该调用真实的后端API
    try {
      // 模拟API调用延迟
      setTimeout(() => {
        const mockResponse = {
          code: 20000,
          data: {
            token: 'mock_token_' + Date.now(),
            user: {
              phone: values.phone,
              id: 'user_' + Date.now()
            }
          },
          message: '登录成功'
        };
        
        console.log('模拟登录响应:', mockResponse);
        
        // 保存token到localStorage
        localStorage.setItem('token', mockResponse.data.token);
        localStorage.setItem('user', JSON.stringify(mockResponse.data.user));
        
        console.log('登录成功，跳转到home页面');
        alert('登录成功！');
        setLoading(false);
        nav('/home');
      }, 1000); // 模拟1秒的网络延迟
      
    } catch (error) {
      console.error('登录失败:', error);
      alert('登录失败，请重试');
      setLoading(false);
    }
    
    // 真实API调用代码（注释掉，因为后端可能没有实现）
    /*
    axios.post('/login', values).then(res => {
      console.log('登录API响应:', res);
      
      // 兼容多种返回结构
      const businessCode = (res && (res as any).code) as number | undefined;
      const status = (res && (res as any).status) as number | undefined;
      const token = (res as any)?.data?.token || (res as any)?.token;
      const message = (res as any)?.message || (res as any)?.msg;

      if (businessCode === 20000 || status === 200 || token) {
        localStorage.setItem('token', token || '');
        localStorage.setItem('user', JSON.stringify((res as any)?.data?.user || {}));
        console.log('登录成功，跳转到home页面');
        alert('登录成功！');
        nav('/home');
      } else {
        console.log('登录失败，返回数据:', res);
        alert(message || '登录失败，请检查手机号和验证码');
      }
    }).catch((error) => {
      console.error('登录请求失败:', error);
      if (error.response) {
        // 服务器返回了错误状态码
        const status = error.response.status;
        const message = error.response.data?.message || error.response.data?.msg;
        alert(`登录失败 (${status}): ${message || '服务器错误'}`);
      } else if (error.request) {
        // 请求已发出但没有收到响应
        alert('网络错误，请检查网络连接');
      } else {
        // 其他错误
        alert('登录失败，请重试');
      }
    });
    */
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const sendCode = () => {
    if(countdown > 0) return;
    setCountdown(5);
    setDisplayCode(null);
    
    // 生成6位随机数字验证码
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    setRandomCode(code);
    console.log('生成的验证码:', code);
    
    const timer = setInterval(() => {
      setCountdown(prev => {
        if(prev <= 1) {
          clearInterval(timer);
          // 倒计时结束后，回显验证码（不自动填充输入框）
          console.log('倒计时结束，回显验证码:', code);
          setDisplayCode(code);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };
  return (
    <div style={{backgroundColor:'#fff',minHeight:'100vh'}}>
      <NavBar onBack={() => nav(-1)} />
      
      <div style={{textAlign:'center',padding:'20px'}}>
        <img src={title} alt="妙手医生" style={{width:'200px',height:'auto',marginBottom:'40px'}}/>
      </div>

      <div style={{padding:'0 24px'}}>
        <Form
          form={form}
          name="login"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item name="phone">
            <div style={{
              display:'flex',
              alignItems:'center',
              borderBottom:'1px solid #d9d9d9',
              paddingBottom:'12px',
              marginBottom:'20px'
            }}>
              <span style={{marginRight:'8px',color:'#666'}}>+86</span>
              <Input
                placeholder="输入手机号"
                style={{border:'none',boxShadow:'none',flex:1}}
                bordered={false}
              />
            </div>
          </Form.Item>

          <Form.Item name="code">
            <div style={{
              display:'flex',
              alignItems:'center',
              borderBottom:'1px solid #d9d9d9',
              paddingBottom:'12px',
              marginBottom:'20px'
            }}>
              {displayCode && countdown === 0 && (
                <span style={{marginRight:'8px', color:'#1677ff', fontSize:'12px'}}>验证码: {displayCode}</span>
              )}
              <Input
                placeholder="输入验证码"
                style={{border:'none',boxShadow:'none',flex:1}}
                bordered={false}
              />
              <Button
                type="primary"
                size="small"
                style={{
                  background:countdown > 0 ? '#ccc' : '#1677ff',
                  border:'none',
                  borderRadius:'4px',
                  padding:'4px 12px',
                  fontSize:'12px'
                }}
                disabled={countdown > 0}
                onClick={sendCode}
              >
                {countdown > 0 ? `${countdown}s` : '获取验证码'}
              </Button>
            </div>
          </Form.Item>

          <Form.Item name="agree" valuePropName="checked">
            <div style={{
              display:'flex',
              alignItems:'flex-start',
              marginTop:'20px',
              padding:'0 8px'
            }}>
              <Checkbox style={{marginTop:'2px'}} />
              <div style={{
                fontSize:'12px',
                color:'#666',
                lineHeight:'1.4',
                marginLeft:'8px'
              }}>
                已阅读并同意
                <span style={{color:'#1677ff'}}>《妙手医生服务协议》</span>
                和
                <span style={{color:'#1677ff'}}>《妙手医生隐私政策》</span>
                、
                <span style={{color:'#1677ff'}}>《妙手医生儿童个人信息保护规则》</span>
              </div>
            </div>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              disabled={loading}
              style={{
                width:'100%',
                height:'48px',
                background: loading ? '#ccc' : '#1677ff',
                border:'none',
                borderRadius:'24px',
                fontSize:'16px',
                marginTop:'20px'
              }}
            >
              {loading ? '登录中...' : '登录'}
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Index
